Skip to content

fix(readiness): serve the published generation during a staged rebuild (#145) - #162

Merged
ViperJuice merged 8 commits into
mainfrom
t3/serve-during-rebuild
Nov 22, 2026
Merged

ViperJuice merged 8 commits into
mainfrom
t3/serve-during-rebuild

Conversation

@ViperJuice

@ViperJuice ViperJuice commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Every staged build, even a quick incremental update, set index_publication_pending on the registry entry for the whole build. Readiness reported that as missing_provenance, so search_code and symbol_lookup failed closed during every update. The published generation is never modified during a staged build, so it can keep serving reads while the build runs.

  • Owner record. Before the read fence goes up, the build records its owner next to the existing writer.lock in .mcp-index/rebuild-owner.json. The record holds the pid, process start time, host, registration id, published generation, target commit and started_at. It is cleared in finally (publish, failure or abort). If it cannot be written, behaviour is the same as before (fail closed).

  • Liveness check. The owner counts as alive only when all of these hold:

    • the record names the current registration and the still-published generation;
    • it was written on this host;
    • the pid exists with the same recorded start time, read from Linux /proc or otherwise psutil create_time();
    • the writer lock is held, checked with a non-blocking flock probe.

    If the start time was not recorded or cannot be read now, the owner counts as dead.

  • Readiness. The rebuild overlay applies only when the owner is alive, the build's target_commit equals the HEAD observed now, and the tracked tree is clean. Readiness then classifies against the published generation and adds a rebuild object. In every other case readiness is the same as before this PR.

  • Query gates. search_code and symbol_lookup (MCP and IndexItClient), RepoResolver.resolve_ready / is_current and StoreRegistry.is_current accept queryable: ready, or stale_commit while a live rebuild targets the current commit. Duck-typed readiness objects fall back to ready.

  • Summary writes are fenced at the write itself.

    • ChunkWriter takes an optional write_fence. It is entered around each batch transaction and each single-chunk write, after the provider call returns.
    • RepoResolver.generation_write_fence takes the repository writer lock without waiting, so no build can begin between the check and the commit. It yields a WriteGate, and unless the gate is ALLOWED the batch stores nothing:
      • FENCED: a staged rebuild owns the generation (the entry is fenced or replaced, or a live rebuild owner holds the lock). The work is obsolete. SummaryGenerationResult.write_fenced reports it.
      • BUSY: another writer (a sync, or mcp-index repository summarize) holds the lock, no rebuild runs and the generation is unchanged. The write is retryable. write_busy reports it.
    • Committed batches always precede any rebuild's snapshot, so they are kept.
    • Admission refusal: while rebuild is set, write_summaries (direct and task mode) and summarize_sample(persist=true) return rebuild_in_progress up front.
    • A fenced write mid-call also returns rebuild_in_progress, with partial counts. A busy write returns a retryable writer_busy with partial counts.
    • Lazy summary entries carry the fence of the generation the query read. A rebuild drops them, before the provider call or at the write. A busy writer requeues them with exponential backoff (2 s doubling, capped at 60 s), at most five times, and the generation is rechecked when they are admitted again; dropping after the last retry is logged. No new entries are enqueued during a rebuild.
  • One git observation per served query. A request-scoped readiness snapshot is used for admission and context creation. Only the post-query recheck observes git again, fresh. A HEAD move or a newly dirty tree during the query returns index_unavailable.

  • Publish swap. The live store's handles are released after publish_generation. A query admitted during the build finishes on its open connection, and the generation recheck then refuses it.

Owner decision (fixed)

Serve from the current published generation during a staged rebuild, reported as stale, and fail closed only if the build's owner has died.

Readiness during a staged build

Situation Before After search_code / symbol_lookup Summary writes
Live owner, same commit, clean tree missing_provenance ready + rebuild Served, response shape unchanged rebuild_in_progress
Live owner, newer commit = HEAD, clean tree missing_provenance stale_commit + rebuild Served, with stale readiness and a note refused (not ready)
Live owner, HEAD moved away from the target, or tracked files edited missing_provenance missing_provenance index_unavailable refused
Owner dead or unprovable (crash, no record, other host, lock not held, pid reused, no readable start time) missing_provenance missing_provenance index_unavailable refused
Build failed (partial_index_failure) missing_provenance missing_provenance index_unavailable refused
stale_commit with no rebuild running stale_commit stale_commit index_unavailable (unchanged) refused (unchanged)
Rebuild begins during a summary provider call n/a n/a n/a nothing stored for that batch; rebuild_in_progress with partial counts, or the lazy entry is dropped
Another (non-rebuild) writer holds the lock at a summary write n/a n/a n/a nothing stored for that batch; retryable writer_busy with partial counts, or the lazy entry is requeued with bounded backoff

Client-visible fields (all additive)

  • readiness.rebuild: {"in_progress": true, "target_commit": "<sha>", "started_at": "<iso>"}, or null.
  • When search_code is served stale, it returns the envelope {"results", "query", "readiness", "note"}. symbol_lookup responses carry readiness and a note when served stale.
  • write_summaries and summarize_sample can return a shared refusal envelope {"error", "code", "tool", "mutation_performed", "retryable": true, "readiness", "message", "remediation"}, with code either rebuild_in_progress or writer_busy, plus summaries_committed. Partial counters (chunks_summarized, summary_chunks_attempted, summary_missing_chunks, or files / total_chunks) are included, plus a note when some work was committed. summaries_committed, the refusal's chunks_summarized / total_chunks, and mutation_performed count only rows this request itself stored, not summaries it generated that another writer stored meanwhile. Task-mode write_summaries returns the same envelope with the task counters. Both codes are branches in both tools' output schemas.
  • SummaryGenerationResult.to_dict() gains write_fenced, write_busy and summaries_committed. These come from a per-call write tally (a ContextVar, isolated per asyncio task), so concurrent calls sharing one writer never count each other's writes. Successful summarize_sample and write_summaries responses are unchanged; summaries_committed appears only in refusal envelopes.
  • LazyChunkWriter.stop() logs one line with the number of pending lazy entries it drops, queued or in flight. It logs counts only, no content.
  • get_status repository rows gain rebuild and, while served stale, show query_status: "serving_stale".
  • HTTP gateway endpoints serve during a same-commit rebuild but keep refusing stale_commit. The admin /search/optimize and /search/rebuild endpoints are unchanged and tracked in a follow-up issue.
  • mcp-index repository summarize (feat(cli): resumable repository summarize summary prefill (#121) #157) already holds the writer lock for its whole run and refuses during a rebuild, so it is unchanged.

Tests (fakes and tmp_path only; uv run --extra dev pytest <files> -n 2 --no-cov)

New file tests/test_issue_145_serve_during_rebuild.py: 45 tests, all passed. They cover:

  • owner liveness and the start-time and psutil cases;
  • same-commit and newer-commit builds served;
  • HEAD moved, dirty tree and dead owner all failing closed;
  • failure and abort clearing the owner;
  • publish swap mid-query;
  • refusal of summary writes, mid-run stop, and lazy enqueue being skipped;
  • at most 2 git status calls per served query, and the post-query recheck.

Added in the third review round:

  • One-file summarize_sample(persist=true) where the rebuild begins during the provider await, by fence flag and by another thread holding the writer lock with a live rebuild owner. Nothing is stored in the old generation and the response is rebuild_in_progress. A no-rebuild control proves the same call does persist.
  • A lazy queue entry where the rebuild begins during the provider call, by fence flag and by writer lock plus live owner: it is dropped and nothing is stored. An already-fenced entry is dropped before any provider call. A control entry with no rebuild is stored.
  • search_code enqueues lazy entries with a generation fence that flips from ALLOWED to FENCED once a rebuild fences the entry.
  • The real write_summaries and summarize_sample rebuild_in_progress responses validate against the advertised output schemas with jsonschema.

Added in the fourth review round (a busy writer vs a rebuild):

  • summarize_sample(persist=true) is parametrized over no rebuild, the fence flag, a rebuild holding the lock with a live owner, and a busy non-rebuild writer. The rebuild cases give rebuild_in_progress, the busy case gives writer_busy, nothing is stored in either, and each response validates against the schema.
  • A lazy entry while a non-rebuild writer holds the lock is requeued, not dropped. It is requeued again, before any provider call, while still busy, and stored once the writer is done. Busy retries are bounded, and the final drop is logged.
  • A lazy entry under a real rebuild (fence flag, or lock plus live owner) is dropped and not requeued.
  • Explicit write_summaries while a non-rebuild writer holds the lock: retryable writer_busy with partial counts, readiness.rebuild null, nothing stored, schema-valid. The retry after the writer finishes persists.
  • Task-backed write_summaries with the first batch fenced or busy returns the shared envelope with the task counters, and it validates against the write_summaries schema.

Added in the fifth review round (committed vs generated):

  • write_summaries over two files, where another writer stores the first file's summaries during its provider call and the second file then hits a busy writer: writer_busy with mutation_performed: false, summaries_committed: 0, chunks_summarized: 0, no note, only the other writer's row stored, schema-valid.
  • The same in task mode: a pass that only completed another writer's row, followed by a busy pass, gives mutation_performed: false, schema-valid.
  • Lazy writer shutdown with one entry backing off and two queued logs "3 pending entries dropped" with no entry content.

Added in the sixth review round (per-call tally):

  • Two overlapping summarize_file_chunks calls on one writer, where only one commits, with the interleaving asserted: the committing call reports summaries_committed: 1, the other 0.
  • A successful summarize_sample carries no summaries_committed, top level or per file.

Results at bc1ff4e:

  • tests/test_issue_145_serve_during_rebuild.py: 45 tests, all passed.
  • The 30 files covering summarization, summary tools, tasks and the stdio and schema contracts: 965 passed, 1 skipped, 0 failed.
  • A broader 65-file run at this head was SIGKILLed (exit 137) at about 41% when the agent's turn was interrupted. There was no failure before the kill and no OOM or memory-pressure evidence. The narrowed rerun above is the deliberate retry. This round changed only summarization.py and one summarize_sample response field.

Results at 05c1cc4:

  • 65 affected files (the same areas as below, plus everything that uses lock_registry or SummaryGenerationResult): 1871 passed, 5 skipped, 0 failed.
  • tests/test_issue_145_serve_during_rebuild.py: 44 tests, all passed.

Results at b574cac:

  • 65 affected files: 1868 passed, 5 skipped, 0 failed.
  • Doc tests that reference SUPPORT_MATRIX: 69 passed.

Earlier results at 4ae09f8 (rebased onto origin/main 9f956e4):

  • 67 affected files (summarization, repository summarize, tasks, stdio and schema contracts, handlers, client, readiness, git index manager, watcher sweep and reconciliation): 1832 passed, 5 skipped, 4 failed. The 4 failures were in test_mcp_server_cli.py, whose fake readiness lacks queryable; fixed with the ready fallback, and those files then passed (84 tests).
  • Doc tests that reference SUPPORT_MATRIX: 69 passed.
  • black and ruff pass on the changed files.
  • test_v13_data_reconciliation.py now passes on the rebased base, after fix(sync): watcher sweep reconciles a new committed change again (#163) #164.

Docs

  • docs/SUPPORT_MATRIX.md: readiness paragraph, state table, write fencing and the single observation per query.
  • README.md and docs/operations/deployment-runbook.md: a note on the rebuild exception.

Refs #145

🤖 Generated with Claude Code

ViperJuice added a commit that referenced this pull request Nov 22, 2026
…rce (#145)

Review follow-up for #162.

- The rebuild overlay now applies only while the live owner's
  target_commit equals the freshly observed HEAD and the tracked tree is
  clean. A HEAD that moved away from the build's target, or tracked
  edits, fall back to the fail-closed missing_provenance. serving_stale
  also requires rebuild.target_commit == current_commit.
- An owner whose process start time was not recorded, or cannot be read
  now, is not provably alive and counts as dead. The start time comes
  from Linux /proc, falling back to psutil create_time() (a core
  dependency) on hosts without /proc.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ViperJuice added a commit that referenced this pull request Nov 22, 2026
… per query (#145)

Second review follow-up for #162.

- Persistent index writes no longer reach a generation a staged rebuild is
  about to replace. While readiness carries `rebuild`, write_summaries
  (including task mode) and summarize_sample(persist=true) return
  code "rebuild_in_progress" with a retry remediation. Right before
  writing they recheck RepoResolver.accepts_writes(ctx) (registry fence and
  file identity, no git), and the same check is the writer's per-batch
  cancel_check, so a rebuild that starts mid-run stops it at the next
  batch and the response says what may be lost. Lazy summary enqueue from
  search_code is skipped during a rebuild. Read-only queries are still
  served.
- A served query now observes `git status` once per checkout: readiness
  classification reuses a request-scoped snapshot (contextvar, carried into
  the search executor thread) through admission and context creation, and
  only the post-query recheck observes git again, fresh. A HEAD move or a
  newly dirty tree during the query returns index_unavailable.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ViperJuice and others added 4 commits November 21, 2026 21:52
#145)

A staged build set index_publication_pending for its whole run, which
readiness reported as missing_provenance, so every update - even a quick
incremental - made search_code/symbol_lookup fail closed.

The build now records its owner next to the repository writer.lock
(.mcp-index/rebuild-owner.json: pid, process start time, host,
registration and published generation, target commit) before the fence
goes up, and clears it in finally (publish, failure or abort). The owner
is alive only while that process exists with the same start time on
this host and still holds the writer lock.

While the owner is alive, readiness classifies the published generation
(ready for a same-commit rebuild, stale_commit while a newer commit is
indexed) and adds an additive `rebuild` object. search_code and
symbol_lookup serve the published generation; stale responses carry the
stale readiness and a note. A dead or unprovable owner keeps
missing_provenance and fails closed; every other non-ready state is
unchanged, and mutating tools still require ready.

The live store's handles are now released after the publish swap rather
than before it, so a query admitted during the build finishes on its open
connection and is then refused by the existing generation recheck.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rce (#145)

Review follow-up for #162.

- The rebuild overlay now applies only while the live owner's
  target_commit equals the freshly observed HEAD and the tracked tree is
  clean. A HEAD that moved away from the build's target, or tracked
  edits, fall back to the fail-closed missing_provenance. serving_stale
  also requires rebuild.target_commit == current_commit.
- An owner whose process start time was not recorded, or cannot be read
  now, is not provably alive and counts as dead. The start time comes
  from Linux /proc, falling back to psutil create_time() (a core
  dependency) on hosts without /proc.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… per query (#145)

Second review follow-up for #162.

- Persistent index writes no longer reach a generation a staged rebuild is
  about to replace. While readiness carries `rebuild`, write_summaries
  (including task mode) and summarize_sample(persist=true) return
  code "rebuild_in_progress" with a retry remediation. Right before
  writing they recheck RepoResolver.accepts_writes(ctx) (registry fence and
  file identity, no git), and the same check is the writer's per-batch
  cancel_check, so a rebuild that starts mid-run stops it at the next
  batch and the response says what may be lost. Lazy summary enqueue from
  search_code is skipped during a rebuild. Read-only queries are still
  served.
- A served query now observes `git status` once per checkout: readiness
  classification reuses a request-scoped snapshot (contextvar, carried into
  the search executor thread) through admission and context creation, and
  only the post-query recheck observes git again, fresh. A HEAD move or a
  newly dirty tree during the query returns index_unavailable.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rebuild_in_progress (#145)

Third review follow-up for #162.

- Summary writes are now checked at the persistence point, after the
  provider call returns. ChunkWriter takes an optional write_fence, a
  context manager entered around each batch transaction and each single
  chunk write. RepoResolver.generation_write_fence takes the repository
  writer lock without waiting and yields whether the registration and
  published generation still accept writes, so no staged build can begin
  between the check and the commit. A fenced batch stores nothing, and
  SummaryGenerationResult.write_fenced reports it; process_scope stops on
  it.
- write_summaries (direct and task mode) and summarize_sample(persist=true)
  pass the fence and return rebuild_in_progress, with partial counts, when
  a write is fenced. Batches committed before the fence are kept, since
  they precede any rebuild's snapshot.
- Lazy summary entries carry the fence of the generation the query read;
  they are dropped before the provider call when already fenced, and
  checked again at the write.
- A shared rebuild_in_progress branch is added to the write_summaries and
  summarize_sample output schemas, with jsonschema validation tests.
- The query gates fall back to `ready` for duck-typed readiness objects
  that lack `queryable`/`serving_stale`/`rebuild`.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ViperJuice
ViperJuice force-pushed the t3/serve-during-rebuild branch from bbaa44b to 4ae09f8 Compare November 22, 2026 03:07
ViperJuice and others added 4 commits November 21, 2026 22:25
…elope for tasks (#145)

Fourth review follow-up for #162.

- The persistent-write fence now yields a WriteGate instead of a bool.
  FENCED means a staged rebuild owns the generation (the entry is fenced
  or replaced, or a live rebuild owner holds the writer lock), so the
  work is obsolete. BUSY means another writer (a sync, or `mcp-index
  repository summarize`) holds the lock while no rebuild runs and the
  generation is unchanged, so the write is retryable.
- write_summaries and summarize_sample(persist=true) return a retryable
  `writer_busy` result with partial counts on BUSY, and keep
  `rebuild_in_progress` for FENCED. SummaryGenerationResult gains
  write_busy, and process_scope stops on either.
- Lazy entries are dropped only on FENCED. On BUSY they are requeued with
  exponential backoff (2 s doubling, capped at 60 s), at most five times,
  with the generation rechecked when they are admitted again; dropping
  after the last retry is logged.
- Task-backed write_summaries builds its refusal with the same shared
  envelope (summary_write_refusal) as the synchronous tool, keeping the
  task counters. writer_busy joins rebuild_in_progress in both tools'
  output schemas, and jsonschema tests cover the direct and task results.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… entries at shutdown (#145)

Fifth review follow-up for #162.

- ChunkWriter counts the rows it actually stores (committed_writes,
  incremented only when _persist_summary stores a row), and
  SummaryGenerationResult gains summaries_committed (in summarize_file_chunks
  and every process_scope result). summaries_written still counts what a
  call generated or completed, which can include rows another writer
  stored during the provider call.
- summary_write_refusal takes an explicit `committed` count, which alone
  decides mutation_performed, the note and `summaries_committed`.
  write_summaries (direct and task mode) and summarize_sample derive their
  refusal counters from it, and summarize_sample file entries report
  summaries_committed. The output schema lists the new field.
- LazyChunkWriter.stop() logs one line with the number of pending entries
  it drops, queued or in flight (including one backing off), without their
  content.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…#145)

Sixth review follow-up for #162.

- Each summarize_file_chunks call, and each lazy queued entry, opens its
  own write tally (a ContextVar, isolated per asyncio task).
  _persist_summary and the write fence record committed, fenced and busy
  writes into the active call's tally. write_fenced, write_busy and
  summaries_committed come from that tally, and process_scope sums
  summaries_committed from its file results. Concurrent calls sharing one
  writer no longer pick up each other's commits through a delta of the
  writer's cumulative counters, which remain only as diagnostics.
- Successful summarize_sample responses are unchanged again:
  summaries_committed appears only in refusal envelopes.

Refs #145

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nce (#145 re-review)

The preflight fence of a queued lazy entry ran before the entry opened
its own write tally, so a worker that inherited an active context (or a
nested call) recorded the entry's BUSY/FENCED outcome into an unrelated
caller's tally. The entry's tally now covers the preflight and every
early return.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ViperJuice
ViperJuice marked this pull request as ready for review November 22, 2026 06:14
@ViperJuice
ViperJuice merged commit bcc0f60 into main Nov 22, 2026
14 checks passed
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T06:17:01.852875Z e460193 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e460193c29

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@property
def queryable(self) -> bool:
"""True when indexed query tools may serve the published generation."""
return self.ready or self.serving_stale

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the documented non-ready query admission contract

During a newer-commit rebuild, this makes stale_commit queryable and allows indexed results instead of the required native-search fallback. The root AGENTS.md MRREADY rollout contract explicitly requires non-ready query paths to return index_unavailable with safe_fallback: "native_search". Labeling the results stale does not preserve that contract. Keep non-ready admission fail-closed, or explicitly reconcile the repository contract with this new exception before enabling it.

AGENTS.md reference: AGENTS.md:L174-L175

Useful? React with 👍 / 👎.

Comment on lines +473 to 474
if readiness is not None and not readiness_queryable(readiness):
return _index_unavailable_response(readiness, "symbol_lookup", symbol=symbol)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Isolate symbol fallback from staging-generation plugins

When a newer-commit rebuild is running, admitting symbol_lookup also exposes the staging plugins, not just the published SQLite generation. EnhancedDispatcher.lookup() falls back to plugins_for(ctx.repo_id) when the published symbol table misses but BM25 supplies an extension hint; staging uses that same repository-keyed plugin set. For example, if the published JavaScript contains a reference to a name and the rebuild adds its definition, the JavaScript plugin's _symbol_cache can return the newly staged definition and its temporary staging path before publication. The generation recheck still passes because the published generation has not changed. Disable plugin fallback while serving a rebuilding generation, or isolate and select plugins by generation.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant